using System;
using System.Collections.Generic;
using roster.Domain;

namespace roster.UI
{
	public class RaidCreationController
	{
		public event Action<IEnumerable<IPlayer>> RaidCreated;
		
		RaidCreationView m_RaidCreationView;
		IEnumerable<IPlayer> m_playerList = new List<IPlayer>();
		IList<IPlayer> m_selectedPlayerList = new List<IPlayer>();
		
		public RaidCreationController(RaidCreationView view)
		{
			m_RaidCreationView = view;
			m_RaidCreationView.RaidCreated += m_RaidCreationView_RaidCreated;
			m_RaidCreationView.PlayerSelected += m_RaidCreationView_PlayerSelected;
			m_RaidCreationView.PlayerUnselected += m_RaidCreationView_PlayerUnselected;
		}
		
		public void CreateRaid(IList<IPlayer> rosterList, IEnumerable<IPlayer> playerList)
		{
			m_playerList = playerList;
			
			foreach (IPlayer player in playerList)
			{
				m_RaidCreationView.AddPlayer(player, rosterList.Contains(player));
			}
			
			m_RaidCreationView.Show();
		}
		
		private void m_RaidCreationView_RaidCreated()
		{
			m_RaidCreationView.Hide();
			
			RaidCreated(m_selectedPlayerList);
		}
		
		private void m_RaidCreationView_PlayerSelected(string playerName)
		{
			IPlayer player = FindPlayerByName(playerName);
			if (player != null)
				m_selectedPlayerList.Add(player);
		}
		
		private void m_RaidCreationView_PlayerUnselected(string playerName)
		{
			IPlayer player = FindPlayerByName(playerName);
			if (player != null)
				m_selectedPlayerList.Remove(player);
		}
		
		private IPlayer FindPlayerByName(string playerName)
		{
			foreach (IPlayer player in m_playerList)
			{
				if (player.Name == playerName)
					return player;
			}
			
			return null;
		}
	}
}
